package com.peng.leetcode.search;

/**
 * FindNumberIn2DArray
 * 剑指 Offer 04. 二维数组中的查找
 * https://leetcode.cn/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
 * <p>
 * Created on 2022/12/9
 *
 * @author lupeng
 */
public class FindNumberIn2DArray {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) {
            return false;
        }
        for (int[] arr : matrix) {
            int i = search(arr, target);
            if (i >= 0 && i < arr.length && arr[i] == target) {
                return true;
            }
        }
        return false;
    }

    int search(int[] arr, int target) {
        int l = 0, r = arr.length;
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (arr[mid] < target) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        return l;
    }
}
